<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-left:10px">教师姓名：</span>
      <el-input @keyup.enter.native="handleFilter" clearable style="width: 140px;" class="filter-item" placeholder="请输入教师姓名" v-model="listQuery.name">
      </el-input>
      <span style="margin-left:10px">所属学校：</span>
      <el-input @keyup.enter.native="handleFilter" clearable style="width: 200px;" class="filter-item" placeholder="请输入关键词" v-model="listQuery.title">
      </el-input>           
      <span style="margin-left:10px">是否认证：</span>
      <el-select v-model="listQuery.audit" placeholder="请选择" style="width: 120px;" clearable>
        <el-option label="是" :value='1'></el-option> 
        <el-option label="否" :value='0'></el-option>
      </el-select>
      <span style="margin-left:10px">手机：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="搜索手机号" v-model="listQuery.mobile" clearable>
      </el-input><br><br>
      <span style="margin-left:10px">所属年级：</span>
      <el-select v-model="listQuery.gradeId" placeholder="请选择" style="width: 140px;" clearable>
        <el-option label="高一" :value='1'></el-option> 
        <el-option label="高二" :value='2'></el-option> 
        <el-option label="高三" :value='3'></el-option> 
        <el-option label="不分年级" :value='4'></el-option> 
      </el-select>
      <span style="margin-left:10px">所属地区：</span>
      <el-cascader
           change-on-select clearable placeholder="全部" expand-trigger="click"
          :options="areas"
          v-model="listQuery.areaIds"
        ></el-cascader>
      <span style="margin-left:10px">是否专家：</span>
      <el-select v-model="listQuery.isExpert" placeholder="请选择" style="width: 120px;" clearable>
        <el-option label="是" :value='1'></el-option> 
        <el-option label="否" :value='0'></el-option> 
        <el-option label="全部" :value='null'></el-option> 
      </el-select>      
      <span style="margin-left:10px">性别：</span>
      <el-select v-model="listQuery.sex" placeholder="请选择" style="width: 200px;" clearable>
        <el-option label="男"   :value='1'></el-option> 
        <el-option label="女"   :value='2'></el-option>
        <el-option label="未知" :value='0'></el-option>
      </el-select>
      <el-button class="filter-item" style="margin-left: 100px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary"  @click="resetButton">重置</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row style="width: 100%">
      <el-table-column v-if='showAllDel' type="selection" width="55" />
      <el-table-column min-width="120" align="center" label="教师姓名" prop="name" />
      <el-table-column min-width="120" align="center" label="所属年级" prop="gradeName" />
      <el-table-column min-width="160" align="center" label="所属地区" prop="labels" />
      <el-table-column min-width="160" align="center" label="所属学校" prop="title" show-overflow-tooltip></el-table-column>
      <el-table-column min-width="120" align="center" label="注册时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.createTime | dateformat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="是否已认证" prop="title" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{row.audit == 1 ? '是' : '否'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="120">
        <template slot-scope="{row}">
          <el-button size="small" type="primary" @click="handleModifyStatus(row)">编辑</el-button>
          <el-button size="small" type="primary" @click="handleToggleAllowSpeak(row)">{{ row.audit | transAudit(false)}}</el-button>
        </template>
      </el-table-column>
    </el-table>
<!--分页-->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="编辑教师信息" :visible.sync="dialogFormVisible" center v-if="dialogFormVisible" :before-close="handleClose">
      <el-form :model="temp" :rules="rules" ref="ruleForm">
        <el-form-item label="教师姓名" label-width="80px" prop="nickName">
          <span>{{temp.name}}</span>
        </el-form-item>
        <el-form-item  label="是否专家">
          <template>
            <el-radio v-model="temp.isExpert" :label="1">是</el-radio>
            <el-radio v-model="temp.isExpert" :label="0">否</el-radio>
          </template>
        </el-form-item>

        <el-form-item label="性别" label-width="120px" prop="gradeId">
          <el-select v-model="temp.sex" placeholder="请选择">
            <el-option label="男" :value='1'></el-option> 
            <el-option label="女" :value='2'></el-option> 
            <el-option label="未知" :value='0'></el-option> 
          </el-select>
        </el-form-item> 
        <el-form-item label="所属年级" label-width="120px" prop="gradeId">
          <el-select v-model="temp.gradeId" placeholder="请选择">
            <el-option label="高一" :value='1'></el-option> 
            <el-option label="高二" :value='2'></el-option> 
            <el-option label="高三" :value='3'></el-option> 
            <el-option label="不分年级" :value='4'></el-option> 
          </el-select>
        </el-form-item>   
        <el-form-item label="所属班级" label-width="120px" prop="className">
          <el-select v-model="temp.className" placeholder="请选择">
            <el-option v-for="item in classIds" :key="item.index" :label="`${item}班`" :value="`${item}班`"></el-option> 
          </el-select>
        </el-form-item>              
        <el-form-item label="所属地区" label-width="120px" prop="gradeId">
          <el-cascader
            change-on-select placeholder="全部" expand-trigger="click"
            :options="areas"
            v-model="temp.areaIds" @change="fetchSchoolData">
          </el-cascader>
          <span class="hint">&nbsp;&nbsp;&nbsp;教师所属地区必须选择到 区 / 县</span>
        </el-form-item>
        <!-- <el-form-item label="所属学校" label-width="120px" prop="schoolId"> -->
        <el-form-item label="所属学校" label-width="120px" prop="schoolName">
          <el-select v-model="schoolOption" placeholder="请选择">
            <el-option v-for="item in schools" :key="item.schoolId" :label="item.schoolName" :value="item.schoolId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教师签名" label-width="80px" prop="intro">
          <Tinymce :height=400 ref="editor" v-model="temp.intro"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="updateForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAreaList, getSchoolsById, updates, getIds, teacherAudit, searchList, getAreateacher } from '@/api/highSchool'
import { getArea } from '@/api/academy'
// import { getToken } from '@/utils/auth' // 验权
import { mapGetters, mapActions } from 'vuex'
import { exportFile } from '@/utils'
import Tinymce from '@/components/Tinymce'

const transAudit = (audit, boolean = true) => {
  if (boolean) return audit == 0 ? '取消认证' : '通过认证'
  return audit == 0 ? '通过认证' : '取消认证'
}
export default {
  name: 'list',
  components: { Tinymce },
  data() {
    return {
      schools: [],
      classIds: [],
      areas: [],
      schoolOption: null,
      areaOption: [],
      version: [],
      userTypes: [],
      inputVisible: false,
      inputValue: '',
      dateformat: '',
      list: null,
      total: null,
      listLoading: true,

      listQuery: {
        areaId: null,
        areaIds: [],
        audit : null,
        gradeId : null,
        isExpert : null,
        name : '',
        mobile: '',
        userType : null,
        pageNo: 1,
        pageSize: 10,
        title: '',
        sex:null
      },
      temp: {
        labels: []
      },
      dialogFormVisible: false,
      rules: {
        // areaId: [{ required: true, message: '请选择所属地区', trigger: 'change' }],
        // schoolId: [{ required: true, message: '请选择所属学校', trigger: 'change' }],
        // userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
      },
      tableKey: 0,
      showAllDel: false,
      multipleSelection: [],
      pageBoolean: {
        delColor: 'primary',
        delText: '批量删除'
      },
      schoolOptions: []
    }
  },
  mounted() {
    this.handleFilter()
    this.fetchAreaData()
    this.getClass()
  },
  filters: {
    transAudit
  },

  methods: {
    handleClose() {
      const that = this
      this.$confirm('数据未保存，确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible = false
        this.listQuery.areaIds = []
        this.listQuery.areaId = null
      }).catch(() => {})
    },
    // 获得班级1-100的数组
    getClass(){
      for(let i = 1; i <= 100; i++){
        this.classIds.push(i)
      }
    },
    // 认证教师
    handleToggleAllowSpeak({ audit, suiId }) {
      teacherAudit({
        audit: audit == 1 ? 0 : 1,
        suiId: suiId
      })
        .then(() => {
          this.$message({
            message: `${transAudit(audit, false)}成功！`,
            type: 'success'
          })
          this.handleFilter()
        }).catch(err => {})
    },
    // 搜索相关的学校
    fetchSchoolData(id) {
      if(id instanceof Array == true){
        id = id[id.length - 1]
      }else{
        id = id
      }
      getSchoolsById(id).then(response => {
        this.schools = response.data
        this.dialogFormVisible = true
      }).catch(err => {})
    },

    fetchAreaData() {
      getAreaList().then(response => {
        this.areas = response.data
      })
    },
    //通过id获取id数组
    getArea(){
      const id = { id : this.temp.areaId }
      getArea(id).then(res => {
        if(res.code == 0) {
          if(res.data.grandFatherId){
            this.listQuery.areaIds.push(res.data.grandFatherId, res.data.fatherId, res.data.id)
          }else if(res.data.fatherId){
            this.listQuery.areaIds.push(res.data.fatherId, res.data.id)
          }else {
            this.listQuery.areaIds.push(res.data.id)
          }
        }
      }).catch(err => {})
    },

    // 翻页的时候
    searchList(params){
      searchList(params).then(res => {
        if(res.code == 0){
          this.total = res.data.total
          this.list = res.data.list
          this.listLoading = false
        }
      }).catch(err => {})
    },

    // 根据所选内容搜索
    handleFilter() {
      this.listQuery.pageNo = 1
      const params = this.listQuery
      if(params.areaIds.length == 0){
        params.areaId = null
      }else {
        params.areaId = params.areaIds[params.areaIds.length - 1]
      }
      const par = { areaId : params.areaId }
      if(params.areaId != null){
        getAreateacher(par).then(res => {
          if(res.code == 0){
            if(res.data.length == 0){
              this.total = 0
              this.list = []
              this.listLoading = false
            }else{
              searchList(params).then(res => {
                if(res.code == 0){
                  this.total = res.data.total
                  this.list = res.data.list
                  this.listLoading = false
                }
              }).catch(err => {})
            }
          }
        })
      }else {
        searchList(params).then(res => {
          if(res.code == 0){
            this.total = res.data.total
            this.list = res.data.list
            this.listLoading = false
          }
        }).catch(err => {})
      }
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      const params = this.listQuery
      this.searchList(params)
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      const params = this.listQuery
      this.searchList(params)
    },
    handleModifyStatus(row) {
      getIds(row.suiId).then(response => {
        this.listQuery.areaIds = []
        this.dialogFormVisible = true
        const { data } = response
        this.temp = data
        // let areaIds = data['areaIds'];
        const aIds = []
        this.getArea()
        this.temp.areaIds = this.listQuery.areaIds
        this.areaOption = aIds
        //获取区域所属学校
        this.schoolOption = data['schoolId']
        this.fetchSchoolData(data['areaId'])
      }).catch(err => {})
    },
    updateForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { temp, schoolOption, areaOption } = this
          const params = {}
          if(temp.areaIds.length != 3){
            this.$message({
              title: '失败',
              message: '教师所属地区必须选择到 区 / 县',
              type: 'error',
              duration: 2000
            })
            return
          }
          params['areaId'] = temp.areaIds[temp.areaIds.length - 1]
          params['gradeId'] = temp['gradeId']
          params['intro'] = temp['intro']
          params['isExpert'] = temp['isExpert']
          params['name'] = temp['name']
          params['schoolId'] = this.schoolOption
          params['sex'] = temp['sex']
          params['suiId'] = temp['suiId']
          params['userType'] = temp['userType']
          params['className'] = temp['className']
          updates(params).then(response => {
            const { code, message } = response
            if (code == 0) {
              this.handleFilter()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }else{
              this.$message({
                title: '失败',
                message: message,
                type: 'error',
                duration: 2000
              })
            }
          }).catch(err => {})
        }
      })
      this.listQuery.areaIds = []
      this.listQuery.areaId = null
    },
    // 重置所输入的搜索内容
    resetButton(){
      this.listQuery.areaId = null
      this.listQuery.areaIds = []
      this.listQuery.audit = null
      this.listQuery.gradeId = null
      this.listQuery.isExpert = null
      this.listQuery.name = ''
      this.listQuery.userType = null
      this.listQuery.pageNo = 1
      this.listQuery.pageSize = 10
      this.listQuery.title = ''
      this.listQuery.sex = null
      this.listQuery.mobile = ''
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.icon-ctx {
  width: 160px;
  height: 80px;
  overflow: hidden;
  margin: 0 auto;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
.hint{
  font-size: 12px;
  color: #999999;
}
</style>